package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettingList) {
        //添加之前需要判断是否已经存在每天的数据
        //如果不存在，才插入，如果存在，就需要更新数据
        if(orderSettingList!=null && orderSettingList.size()>0){
            for (OrderSetting orderSetting : orderSettingList) {
                Date orderDate = orderSetting.getOrderDate();
                //判断是否存在
                int flagCount = orderSettingDao.findCountByDate(orderDate);
                if(flagCount>0){
                    //此日期数据存在
                    orderSettingDao.update(orderSetting);
                }else {
                    //此日期数据不存在
                    orderSettingDao.addOrderSetting(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map<String,Object>> findOrderSettingByMonth(String date) {
        //此时从controller传入的date格式为2020-03
        //查询当月的比较日期大于等于1号，小于等于31即为当月
        String beginDate = date +"-01";
        String endDate = date + "-31";
        //此时调用dao方法，需传入两个参数，所有封装为map集合传入
        Map<String,String> map = new HashMap<>();
        map.put("beginDate",beginDate);
        map.put("endDate",endDate);
        List<OrderSetting> list = orderSettingDao.findOrderSettingByMonth(map);


        List<Map<String,Object>> resultList = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            int orderDate = orderSetting.getOrderDate().getDate();
            int number = orderSetting.getNumber();
            int reservations = orderSetting.getReservations();
            Map<String, Object> resultMap = new HashMap<>();
            //{ date: 1, number: 120, reservations: 1 },
            resultMap.put("date",orderDate);
            resultMap.put("number",number);
            resultMap.put("reservations",reservations);
            resultList.add(resultMap);
        }
        return resultList;
    }

    @Override
    public void updateNumberByDate(OrderSetting orderSetting) {
        //此时应先查询当前是否已经进行了预约设置
        int flagCount = orderSettingDao.findCountByDate(orderSetting.getOrderDate());
        if(flagCount>0){
            //此前已经进行过预约设置，此时只需要修改
            orderSettingDao.update(orderSetting);
        }else{
            //此前未进行过预约设置
            orderSettingDao.addOrderSetting(orderSetting);
        }
    }
}
